<template>
    <div class="app-container produce-task">
        <el-tabs v-model="queryParams.taskStep" :before-leave="onTabChange">
            <el-tab-pane label="所有任务" name="all" />
            <template v-for="item in taskStepEnum">
                <el-tab-pane v-if="item.value != taskStepEnum.news.value" :label="item.label" :name="item.value" />
            </template>
            <el-tab-pane label="取消" name="cancel" />
        </el-tabs>

        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="80px">
            <el-form-item label="任务编号">
                <el-input v-model="queryParams.taskNo" placeholder="请输入物料编号" clearable />
            </el-form-item>
            <el-form-item label="任务类型">
                <el-select v-model="queryParams.taskCategory" filterable clearable>
                    <el-option v-for="item in dict.type.mos_task_type" :value="item.value" :label="item.label" />
                </el-select>
            </el-form-item>
        <!--    <el-form-item label="合同编号">
                <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable />
            </el-form-item> -->
            <el-form-item label="关联合同">
                <el-input v-model="queryParams.contractName" placeholder="请输入合同编号" clearable />
            </el-form-item>
            <el-form-item label="发布时间">
                <el-date-picker v-model="dateRange" style="width: 215px" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="mb8">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="onAdd" v-hasPermi="['oms:omstask:add']">
                新建任务
            </el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['oms:omstask:export']">
                导出
            </el-button>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
        <el-table v-loading="loading" :data="tableList" @sort-change="onSortChange">
            <el-table-column label="任务编号" prop="taskNo">
                <div class="task-no" slot-scope="{row}">
                    <span class="cell-icon" v-if="Number(row.taskTopping)">置顶</span>
                    <span class="cell-icon" v-if="Number(row.taskBack)">驳回</span>
                    <span class="cell-icon" v-if="row.isBuShu=='bushu'">补数</span>
                    {{ row.taskNo }}
                </div>
            </el-table-column>
            <el-table-column label="商品信息" prop="productList">
                <div slot-scope="{row}">
                    <div class="table-cell-img">
                        <el-image :preview-src-list="row.productList.map(item => item.productImage)"
                            :src="row.productList[0].productImage">
                            <i slot="error" class="el-icon-picture-outline"></i>
                        </el-image>
                    </div>
                     <div>{{ row.productList[0].productName }}</div>
                    <!-- <div v-if="row.productList.length>0" v-for="item in row.productList>0">{{ item.productName }}</div> -->
                </div>
            </el-table-column>
            <el-table-column label="颜色" prop="productList[0].productColour" sortable="custom" width="170" />
            <el-table-column label="规格" prop="productList[0].productSku" sortable="custom" width="170" />
            <el-table-column label="数量" prop="productList[0].productNum" sortable="custom" width="170" />
            <el-table-column label="发布时间" prop="releaseTime" sortable="custom" width="170" />
            <el-table-column label="关联合同" prop="contractName" sortable="custom" width="170" />
             <el-table-column label="补数数量" prop="compnengtsNum" sortable="custom" width="170" />
            <el-table-column label="任务类型" prop="taskCategory">
                <template slot-scope="{row}">
                    <span v-for="item in dict.type.mos_task_type" v-show="row.taskCategory === item.value">
                        {{ item.label }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="生产状态" prop="status">
                <template slot-scope="{row}">
                    <span v-for="item in taskStatus" v-show="row.status === item.value">{{ item.label }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="330" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                    <el-button size="mini" type="text" @click="onDetail(row)">
                        详情
                        <span class="dot" v-if="Number(row.haveRemark)" />
                    </el-button>
                    <el-button size="mini" type="text" @click="onCancel(row)"
                        v-if="row.taskStep === taskStepEnum.news.value"
                        :disabled="row.status === taskStatus.cancel.value" v-hasPermi="['oms:omstask:remove']">取消
                    </el-button>
                    <el-button @click="onGetTaskStep(row, taskStepEnum.news.value, taskStepEnum.news.permi)" size="mini"
                        type="text" v-hasPermi="[taskStepEnum.news.permi]">领料
                    </el-button>
                    <!--订单成品类型-->
                    <template v-if="row.taskCategory === taskTypeEnum.production">
                        <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.ball.value"
                            @click="onGetTaskStep(row,taskStepEnum.ball.value,taskStepEnum.ball.permi)"
                            v-hasPermi="[taskStepEnum.ball.permi]">插球
                        </el-button>
                        <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.plating.value"
                            @click="onGetTaskStep(row,taskStepEnum.plating.value,taskStepEnum.plating.permi)"
                            v-hasPermi="[taskStepEnum.plating.permi]">电镀
                        </el-button>
                        <el-button v-if="row.isPainting==1" size="mini" type="text"
                            :disabled="row.taskStep < taskStepEnum.painting.value"
                            @click="onGetTaskStep(row,taskStepEnum.painting.value,taskStepEnum.painting.permi)"
                            v-hasPermi="[taskStepEnum.painting.permi]">彩绘
                        </el-button>
                        <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.packing.value"
                            @click="onGetTaskStep(row,taskStepEnum.packing.value,taskStepEnum.packing.permi)"
                            v-hasPermi="[taskStepEnum.packing.permi]">包装
                        </el-button>
                    </template>
                    <!--备货半成品类型-->
                    <template v-if="row.taskCategory === taskTypeEnum.half">
                        <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.ball.value"
                            @click="onGetTaskStep(row,taskStepEnum.ball.value,taskStepEnum.ball.permi)"
                            v-hasPermi="[taskStepEnum.ball.permi]">插球
                        </el-button>
                        <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.plating.value"
                            @click="onGetTaskStep(row,taskStepEnum.plating.value,taskStepEnum.plating.permi)"
                            v-hasPermi="[taskStepEnum.plating.permi]">电镀
                        </el-button>
                        <el-button v-if="row.isPainting==1" size="mini" type="text"
                            :disabled="row.taskStep < taskStepEnum.painting.value"
                            @click="onGetTaskStep(row,taskStepEnum.painting.value,taskStepEnum.painting.permi)"
                            v-hasPermi="[taskStepEnum.painting.permi]">彩绘
                        </el-button>
                    </template>
                    <!--备货半成品包装-->
                    <template v-if="row.taskCategory === taskTypeEnum.halfPacking">
                        <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.packing.value"
                            @click="onGetTaskStep(row,taskStepEnum.packing.value,taskStepEnum.packing.permi)"
                            v-hasPermi="[taskStepEnum.packing.permi]">包装
                        </el-button>
                    </template>
                    <el-button size="mini" type="text" :disabled="row.taskStep < taskStepEnum.complete.value"
                        v-if="row.status !== taskStatus.complete.value"
                        @click="onGetTaskStep(row,taskStepEnum.complete.value,taskStepEnum.complete.permi)"
                        v-hasPermi="[taskStepEnum.complete.permi]">完成
                    </el-button>
                    <el-button size="mini" type="text" @click="onTopping(row)">
                        {{ row.taskTopping === toppingEnum.yes ? '取消置顶' : '置顶' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!--任务处理-->
        <el-dialog :title="taskHandleTitle" :visible="showTaskHandle" width="640px" append-to-body
            :close-on-click-modal="false" :close-on-press-escape="false" @close="taskHandleClose">
            <action v-loading="popoverLoading" :data="stepInfo" :step="step" :empty-tips="stepTips"
                :has-permi="hasPermi" @complete="onHandleComplete" @showNeedsData="showNeedsData" />
        </el-dialog>
        <el-dialog title="生产目标列表" :visible.sync="dialogVisible" width="30%">
            <el-table v-loading="loading" :data="tableList1">
                <el-table-column label="物料编号" prop="productNo" show-overflow-tooltip />
                <el-table-column label="物料名称" prop="productName" />
                <el-table-column label="规格" prop="productSku" />
                <el-table-column label="数量" prop="productNum" />
                <el-table-column label="颜色" prop="productColour" />
                <el-table-column label="操作" width="100" class-name="small-padding fixed-width">
                    <template slot-scope="{row}">
                        <el-button size="mini" type="text" @click="complement(row)">补数</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="输入补数数量" :visible="dialogVisibleNumber" width="30%" :show-close="false">
            <el-input placeholder="请输入补数数量" v-model="dialogVisibleNumberInput"/>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleNumberCancel">取 消</el-button>
                <el-button type="primary" @click.stop="dialogVisibleNumberSs">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        handleEnum,
        responseEnum,
        taskStatus,
        taskStepEnum,
        taskTypeEnum,
        toppingEnum
    } from "../../../const/const";
    import {
        cancelTask,
        getTaskList,
        getTaskStep,
        toppingTask,
        getTaskProductListByTaskId,
        Complement
    } from "./api";
    import Api from "./api";
    import _ from "lodash";
    import Action from "./action";

    export default {
        name: "Produce/task",
        dicts: ['mos_task_type'],
        components: {
            Action
        },
        data() {
            return {
                taskCategoryComplement:null,//补数需要提交的任务类型
                isBuShu:null,
                taskId:null,
                productId: null,
                productNum: null,
                dialogVisibleNumberInput: '',
                dialogVisibleNumber: false,
                dialogVisible: false,
                handleEnum,
                // 任务步骤（状态）
                taskStepEnum,
                taskStatus,
                toppingEnum,
                taskTypeEnum,
                // 日期范围
                dateRange: [],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    taskNo: null,
                    contractNo: null,
                    contractName:null,
                    taskCategory: null,
                    taskStep: 'all',
                    status: null,
                    orderByColumn: null,
                    isAsc: null
                },
                // 遮罩层
                loading: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 表格数据
                tableList: [],
                tableList1: [],
                // 操作
                showTaskHandle: false,
                popoverLoading: false,
                step: null,
                stepInfo: [],

                stepTips: '加载中...',

                // 操作权限
                hasPermi: null,
            };
        },
        computed: {
            taskHandleTitle() {
                let title = '';
                Object.keys(taskStepEnum).forEach(key => {
                    if (taskStepEnum[key].value === this.step) {
                        title = `${taskStepEnum[key].label}`;
                    }
                })
                return title;
            }
        },
        beforeCreate() {
            // 当前标签优先从路由获取（首页跳转过来带参数）
            this.queryParams.taskStep = this.$route.query.activeTab || this.queryParams.taskStep
        },
        created() {
            this.getList();
        },
        methods: {
            dialogVisibleNumberCancel(){
                this.productId = null
                this.dialogVisibleNumberInput = ''
                this.productNum = null
                this.taskId=null
                this.dialogVisibleNumber = false
            },
            dialogVisibleNumberSs() {
                 this.loading = true;
                Complement(this.productId, this.dialogVisibleNumberInput, this.productNum,this.taskId,this.isBuShu).then(res => {
                    if (res.code == responseEnum.success) {
                        this.$message.success("操作成功");
                        this.taskId=null
                        this.productId = null
                        this.dialogVisibleNumberInput = ''
                        this.productNum = null
                        this.dialogVisibleNumber = false
                        this.getList();
                    } else {
                        this.$message.error(res);
                    }
                }).finally(() => this.loading = false)
            },
            complement(row) {
                this.productId = row.productId
                this.productNum = row.productNum
               this.taskId=row.taskId
                this.dialogVisibleNumber = true
                this.$forceUpdate()
            },
            showNeedsData(e) {
                this.isBuShu=e.types;
                this.loading = true;
                this.dialogVisible = true
                getTaskProductListByTaskId({
                    taskId: e.taskId
                }).then(res => {
                    if (res.code === responseEnum.success) {
                        this.tableList1 = res.data || [];
                    }
                }).finally(() => this.loading = false);
            },
            /** 查询列表 */
            getList() {
                this.loading = true;
                const params = {
                    ...this.queryParams
                };
                if (this.queryParams.taskStep == 'all') {
                    delete params.taskStep;
                }
                if (this.queryParams.taskStep == 'cancel') {
                    delete params.taskStep;
                    params.status = taskStatus.cancel.value;
                }

                getTaskList(this.addDateRange(params, this.dateRange)).then(res => {
                    if (res.code === responseEnum.success) {
                        this.tableList = res.rows;
                        this.total = res.total;
                        this.$forceUpdate()
                    }
                }).finally(() => this.loading = false);
            },
            /**
             * 新建任务
             */
            onAdd() {
                this.$router.push({
                    path: '/ProduceTask/add'
                })
            },
            /**
             * 切换标签
             */
            onTabChange(val) {
                this.queryParams.taskStep = val;
                this.queryParams.status = null;
                this.handleQuery();
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.queryParams = this.$options.data().queryParams;
                this.handleQuery();
            },
            /**
             * 排序
             */
            onSortChange({
                order,
                prop
            }) {
                this.queryParams.orderByColumn = prop;
                this.queryParams.isAsc = order ? order.replace(/ending/, '') : null;
                this.handleQuery();
            },
            /** 取消按钮操作 */
            onCancel(row) {
                this.$modal.confirm('确认取消任务吗？').then(() => {
                    const loading = this.$loading({
                        lock: true
                    });
                    cancelTask(row.taskId).then(res => {
                        if (res.code === responseEnum.success) {
                            this.getList();
                            this.$message.success("任务已经取消");
                        } else {
                            this.$message.error(res.msg);
                        }
                    }).finally(() => loading.close())
                });
            },

            /**
             * 任务处理
             */
            onGetTaskStep(row, type, hasPermi) {
                this.taskCategoryComplement=row.taskCategory;
                this.showTaskHandle = true;
                this.popoverLoading = true;
                this.step = type;
                this.hasPermi = hasPermi;
                getTaskStep(row.taskId, type).then(res => {
                    if (res.code === responseEnum.success && res.rows && res.rows.length) {
                        this.stepInfo = res.rows;
                    } else {
                        this.$message.error(res.msg);
                    }
                }).finally(() => this.popoverLoading = false)
            },
            /**
             * 任务操作完成回调
             */
            onHandleComplete() {
                this.getList();
                this.taskHandleClose();
            },

            /**
             *
             */
            taskHandleClose() {
                this.showTaskHandle = false;
                this.stepInfo = [];
            },

            /**
             * 跳转详情
             */
            onDetail(row) {
                this.$router.push({
                    name: 'taskDetail',
                    query: {
                        taskId: row.taskId,
                        taskCategory: row.taskCategory
                    }
                })
            },

            /**
             * 置顶操作
             */
            onTopping(row) {
                const type = row.taskTopping === toppingEnum.yes ? toppingEnum.no : toppingEnum.yes;
                toppingTask({
                    taskId: row.taskId,
                    type
                }).then(res => {
                    if (res.code === responseEnum.success) {
                        row.taskTopping = type;
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            },
            /** 导出按钮操作 */
            handleExport() {
                let exportParams = {
                    pageNum: 1,
                    pageSize: 1000000,
                    taskNo: this.queryParams.taskNo,
                    taskCategory: this.queryParams.taskCategory,
                    status: this.queryParams.status,
                    orderByColumn: this.queryParams.orderByColumn,
                    isAsc: this.queryParams.isAsc
                }
                this.download('oms/omstask/export', {
                    ...exportParams
                }, `task_${new Date().getTime()}.xlsx`)
            }
        }
    };
</script>

<style lang="scss" scoped>
    .produce-task {
        .popover-item {
            ::v-deep.el-button {
                margin-left: 10px;
            }
        }
    }

    .dot,
    .cell-icon {
        display: inline-block;
        background: #e87070;
        border-radius: 180px;
        color: #fff;
    }

    .dot {
        width: 8px;
        height: 8px;
    }

    .task-no {
        word-break: break-word;

        span {
            display: inline-block;
            margin-right: 5px;
        }
    }

    .cell-icon {
        width: 30px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        font-size: 12px;
    }
</style>
